<?php
$dpvr_include = true;
require_once('dpvr.php');
asort($GLOBALS['formats']);
asort($GLOBALS['languages']);

if(empty($_GET['sort'])) $_GET['sort'] = $config['sort_by'];
if(empty($_GET['dir'])) $_GET['dir'] = $config['sort_how'];
if(empty($_REQUEST['op'])) $_REQUEST['op'] = '';

switch($_REQUEST['op']) {
  //add
  case 'add':
    //check to make sure the file exists
    if(file_exists($config['dpvr_dir'].$configData['xml_file'])) {

      $silent = true;
    
      //create a SimpleXML object
      $xml = simplexml_load_file($config['dpvr_dir'].$configData['xml_file']);
      
      $cleanName = htmlspecialchars(trim(stripslashes($_POST['name'])));
      
      print_r($_REQUEST);
      
      if ($_REQUEST['daily'] == 1) {
        $lastDlEpURL = 'http://www.thetvdb.com/api/GetEpisodeByAirDate.php?apikey='.PHPTVDB_API_KEY.'&seriesid='.trim($_REQUEST['id']).'&airdate='.trim($_REQUEST['lastDlDate']);
        $lastEpXML = simplexml_load_file($lastDlEpURL);
        if (!isset($lastEpXML['Error'])) {
          $season = (int)$lastEpXML->Episode->SeasonNumber;
          $episode = (int)$lastEpXML->Episode->EpisodeNumber;
        }
      } else {
        $season = trim($_POST['season']);
        $episode = trim($_POST['episode']);
      }

      if ($season == 0)
        $season = 1;
      
      // create a new instance of ShowInfo
      $newShow = new ShowInfo($xml, $_POST['id'], $cleanName);

      // set the show info parts that are user specified
      $newShow->format = trim($_POST['format']);
      $newShow->language = trim($_POST['language']);
      $newShow->dlSeason = $season;
      $newShow->dlEpisode = $episode;
      print "daily:".$_REQUEST['daily']."==1\n";
      if ($_REQUEST['daily'] == 1) {
        $newShow->dlAirdate = strtotime($_REQUEST['lastDlDate']);
        print "setting it to ".strtotime($_REQUEST['lastDlDate'])."\n";
      } else {
        $newShow->dlAirdate = 0;
        print "setting it to 0\n";
      }
      $newShow->poster = trim($_POST['poster']);
      $newShow->dfa = trim($_POST['dfa']);
      $newShow->daily = trim($_POST['daily']);
      
      // fill in any other info from TVDB/TVRage
      $newShow->update();
      
      print saveXML($xml) ? 1 : 0;
    }

    exit();
  
  //edit
  case 'edit':
  
    $silent = true;
  
    //check to make sure the file exists
    if(file_exists($config['dpvr_dir'].$configData['xml_file'])) {
      //create a SimpleXML object
      $xml = simplexml_load_file($config['dpvr_dir'].$configData['xml_file']);
      
      $editShow = new ShowInfo($xml, $_POST['id']);

      $timestamp = false;
      if ((int)$editShow->daily == 1) {
        $lastDlEpURL = 'http://www.thetvdb.com/api/GetEpisodeByAirDate.php?apikey='.PHPTVDB_API_KEY.'&seriesid='.trim($_REQUEST['id']).'&airdate='.trim($_POST['dlAirdate']);
        $lastEpXML = simplexml_load_file($lastDlEpURL);
        if (!isset($lastEpXML['Error'])) {
          $season = (int)$lastEpXML->Episode->SeasonNumber;
          $episode = (int)$lastEpXML->Episode->EpisodeNumber;
          $airdate = strtotime($_POST['dlAirdate']);
          $timestamp = true;
        } else {
          $season = trim($_POST['dlSeason']);
          $episode = trim($_POST['dlEpisode']);
          $airdate = 0;
          $timestamp = true;
        }
      } else {
        $season = trim($_POST['dlSeason']);
        $episode = trim($_POST['dlEpisode']);
        $airdate = 0;
        $timestamp = true;
      }

      $editShow->dlSeason = $season;
      $editShow->dlEpisode = $episode;
      $editShow->dlAirdate = $airdate;
      if ($timestamp)
        $editShow->dlTimestamp = 0;
      $editShow->language = trim($_POST['language']);
      $editShow->format = trim($_POST['format']);
      $editShow->poster = trim($_POST['poster']);
      $editShow->tvrageurl = trim($_POST['tvrageurl']);
      $editShow->dfa = trim($_POST['dfa'] == "on" ? 1:0);
      
      $editShow->update();
      
      $saved = saveXML($xml);
      header('Location: ' . $_SERVER['REQUEST_URI'] . '#' . urlencode(trim($_POST['name'])));
    }
    else {
      header('Location: index.php');
    }
    
    exit();
  
  //delete
  case 'delete':    
    //check to make sure the file exists
    if(file_exists($config['dpvr_dir'].$configData['xml_file'])) {
      //create a SimpleXML object
      $xml = simplexml_load_file($config['dpvr_dir'].$configData['xml_file']);
      
      //find index to remove
      $i = 0;
      foreach($xml->show as $show) {
        if($show->attributes()->seriesID == $_POST['id']) {
          $remove = $i;
        }
        $i++;
      }
      
      //remove it
      if(isset($remove)) {
        unset($xml->show[$remove]);
      }
      
      //write updated xml file
      print saveXML($xml) ? 1 : 0;
    }
    
    exit();
    
  //get posters
  case 'get_posters':
  
    if ($_REQUEST['showID'] != '')
      $show = array(TV_Shows::findById($_REQUEST['showID']));
    else
      $show = TV_Shows::search($_REQUEST['showName']);

    if($show) {
      
      if(count($show) > 0) {
        //1 match found
        if(count($show) == 1) {
          $showID = $show[0]->id;
        }
        //2+ matches found, use first match with an exact name match
        else {
          foreach($show as $curShow) {
            if(strtolower($curShow->seriesName) == strtolower(stripslashes($_REQUEST['showName']))) {
              $showID = $curShow->id;
              break;
            }
          }
        }

        //exact match found
        if($showID > 0) {

          // unfortunately the php tvdb library doesn't support posters for some reason so I'll do it on my own for now
          $seriesXML = file_get_contents('http://thetvdb.com/api/'.PHPTVDB_API_KEY.'/series/'.$showID.'/banners.xml');
          $xml = simplexml_load_string($seriesXML);

          $posters = array();
          if($xml) {
            $banners = $xml->xpath('/Banners/Banner');
            
          
            for ($i = 0; $i < count($banners) && count($posters) < 6; $i++) {
              if ($banners[$i]->BannerType != "poster")
                continue;
                
              $posters[] = $configData['thetvdb']['small_poster']. $banners[$i]->BannerPath;
            }
          }
          print implode(',', $posters);
        }
      }
    }
    
    exit();
    
    
  case 'convertXML':
  
    $silent = true;
  
    convertFromHellaVCR();
    header("Location: index.php");
    exit();
    
  case 'scrape_newzbin':
  
    $silent = true;
    
    getTVRageURL($_REQUEST['report']);

    exit();    
    
}

function getTVRageURL ($newzbinID) {

  $matchResult = preg_match("/^\d+$/", $newzbinID);

  // if it's not an ID directly try an URL
  if ($matchResult == 0) {
    $matchResult = preg_match("/^http:\/\/.*newzbin\.com\/browse\/post\/(\d+)\/$/", $newzbinID, $matches);
    
    // if nothing then error out to the ajax
    if ($matchResult == 0) {
      print "0|ERROR: Invalid Newzbin ID/URL.\n\nExpecting an ID (a number) or the URL of a report (http://*.newzbin.com/browse/post/xxxxxxx/).";
      return;
    } else
      $newzbinID = $matches[1];
  }
    
  $result = downloadFromNewzbin($newzbinID);
  
  $matchResult = preg_match("/^http:\/\/www\.tvrage\.com\/(.+)\/episodes\/\d+\/\d+x\d+/", trim($result[2]), $matches);
  if ($matchResult != 0) {
    print "1|http://www.tvrage.com/$matches[1]/";
    return;
  } else {
    print "0|ERROR: Unable to parse TVRage URL: $result[2]";
    return;
  }
  
  return;
}

//
function sortShows($show1, $show2) {
  global $configData;
  $by = $_GET['sort'];
  $dir = $_GET['dir'];

  switch($by) {
    case 'upcoming':
      if(empty($show1->nextAirdate)) $show1->nextAirdate = $configData['index']['unknown_timestamp'];
      if(empty($show2->nextAirdate)) $show2->nextAirdate = $configData['index']['unknown_timestamp'];
      
      // put ended shows at the bottom
      if(strtolower($show1->status) == 'ended') return ($dir == 'desc') ? -1 : 1;
      if(strtolower($show2->status) == 'ended') return ($dir == 'desc') ? 1 : -1;
      
      // if they air on the same day lets give alternate sorting
      if((int)$show1->nextAirdate == (int)$show2->nextAirdate) {

        // alphabetical if they're unknown
        if ($show1->nextAirdate == $configData['index']['unknown_timestamp'])
          return strncmp($show1->seriesName, $show2->seriesName, 1);

        // by air hour if not
        else
          return ((int)date("G", (int)$show1->airs) < (int)date("G", (int)$show2->airs)) ? -1 : 1;
      }

      if($dir == 'desc') return (intval($show1->nextAirdate) < intval($show2->nextAirdate)) ? 1 : -1;
      else return (intval($show1->nextAirdate) < intval($show2->nextAirdate)) ? -1 : 1;
      break;
    case 'downloaded':
      $show1_last = 0;
      if($show1->downloads) {
        foreach($show1->downloads->download as $d) {
          $show1_last = $d->timestamp;
        }
      }
      $show2_last = 0;
      if($show2->downloads) {
        foreach($show2->downloads->download as $d) {
          $show2_last = $d->timestamp;
        }
      }
      if($show1_last == $show2_last) return 0;
      if($dir == 'desc') return (intval($show1_last) < intval($show2_last)) ? -1 : 1;
      else return (intval($show1_last) < intval($show2_last)) ? 1 : -1;
      break;
    case 'name':
    default:
      return ($dir == 'desc' ? strcmp(strtolower($show2->seriesName), strtolower($show1->seriesName)) : strcmp(strtolower($show1->seriesName), strtolower($show2->seriesName)));
  };
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>dPVR/<?php print $configData['version']; ?></title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <script type="text/javascript" src="js/mootools-1.2-core.js"></script>
  <script type="text/javascript" src="js/mootools-1.2-more.js"></script>
  <script type="text/javascript" src="js/dpvr.js"></script>
  <link type="text/css" rel="stylesheet" media="all" href="css/main.css" />
<script type="text/javascript" src="js/bsn.AutoSuggest_2.1.3.js" charset="utf-8"></script>
<link rel="stylesheet" href="css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />
  <link type="text/css" rel="stylesheet" media="only screen and (max-device-width: 480px)" href="css/iphone.css" />
</head>
<body>
<div id="outerWrapper">
  <div id="titleBar">
    <div id="addWrapper">
<?php if(file_exists($config['dpvr_dir'].$configData['xml_file'])) { ?>
      <a href="#" title="Add Show" id="addButton"><img alt="" src="images/add.png" /> Add Show</a>
<?php } ?>
    </div>
    <div class="version"><?php print $configData['version']; ?></div>
  </div>
<?php if(file_exists($config['dpvr_dir'].$configData['xml_file'])) { ?>
  <div id="showWaiting" class="errorBox">Scanning show information, please wait</div>
<?php } ?>
  <div id="formWrapper" class="formWrapper">
    <table cellpadding="0" cellspacing="0" border=0>
      <tr>
        <th>Show Name:</th>
        <td>
          <div id="addShowNameDiv" style="display: none;"><h1><span id="addShowNameText"></span>&nbsp;&nbsp;&nbsp;<input type="button" size="2" value="Change" id="addShowNameChangeButton"></h1></div>
          <div id="addShowName"><input id="showNameSearch" type="text" autocomplete="off"/></div>
          <input id="showID" type="hidden"/><input id="showName" type="hidden"/>
        </td>
        <td rowspan="5" style="vertical-align: top;">
          <div id="postersWrapper" class="postersWrapper"><div class="selectPosters" id="selectPosters"><!--<img id="postersLoading" class="postersLoading" alt="" src="images/loading_posters.gif" />--></div></div>
        </td>
      </tr>
      <tr>
        <th></th>
        <td>
          <input type="checkbox" id="showFullSeries" /> Download Full Series<br />
          <input type="checkbox" id="downloadFirstAvailable"/> Download First Available<br />
          <input type="checkbox" id="dailyShow"/> Show Airs Daily (no season/episode)
        </td>
      </tr>
      <tr>
        <th>
          <div id="dlSeasonEpText">Last Episode Downloaded:</div>
          <div id="dlDateText" style="display: none;">Last Date Downloaded:</div>
        </th>
        <td>
          <div id="dlSeasonEpDiv"><input type="text" id="showSeason" size="2" /> x <input type="text" id="showEpisode" size="2" /></div>
          <div id="lastDlDateDiv" style="display: none;"><input type="text" id="lastDlDate" size="8"> (ie. <?php print date("Y-m-d"); ?>)</div>
          <input type="hidden" id="showSeasonOrig" /><input type="hidden" id="showEpisodeOrig" />
          <input type="hidden" id="lastDlDateOrig" />
        </td>
      </tr>
      <tr>
        <th>Format:</th>
        <td>
          <select id="showFormat">
            <option value=""></option>
            <?php foreach($GLOBALS['formats'] as $id => $format) { ?>
            <option value="<?php print $id; ?>" <?php print $format == 'x264' ? 'selected="selected"' : ''; ?>><?php print $format; ?></option>
            <?php } ?>
          </select>
        </td>
      </tr>
      <tr>
        <td colspan=2><a href="#" id="add_link" class="addAdvancedSettings">Advanced Settings >></a></td>
      </tr>
      <tr class="advancedAdd" style="display: none;">
        <td colspan=3>Submit a Newzbin report ID/URL to associate this show to a Newzbin report's TVRage URL</td>
      </tr>
      <tr class="advancedAdd" style="display: none;">
        <th>Newzbin Report URL/ID:</th>
        <td colspan=2><input type="text" id="add_newzbinid" /> <input type="button" id="add_doNewzbinID" class="addAdvancedScrapeNewzbin" value="Get Info" /></td>
      </tr>
      <tr class="advancedAdd" style="display: none;">
        <th>TVRage URL:</th>
        <td colspan=2>
          <div id="add_tvrageurl_div"><?php print (!empty($show->tvrageurl)) ? "<a class=\"tvrage_link\" href=\"$show->tvrageurl\">".htmlspecialchars_decode($show->tvrageurl)."</a>" : "n/a"; ?></div>
          <input type="hidden" id="add_tvrageurl" name="tvrageurl" value="<?php print $show->tvrageurl; ?>">
        </td>
      </tr>
      <tr>
        <th></th>
        <td>
          <br />
          <a href="#" id="addShow" class="addShow"><img alt="" src="images/save.png" /> Save</a>
          <a href="#" id="cancelShow" class="cancelShow"><img alt="" src="images/cancel.png" /> Cancel</a>
        </td>
      </tr>
    </table>
  </div>
  <div id="sortBar">
    <table style="width: 100%; border: 0px solid;">
      <tr>
        <td align=left>sort by&nbsp;
        <?php
        $sort_by = array('name', 'upcoming', 'downloaded');
        foreach($sort_by as $name) {
        print '<a href="index.php?sort=' . $name . '&dir=' . ($_GET['sort'] == $name && $_GET['dir'] == 'asc' ? 'desc' : 'asc') . '" class="' . ($_GET['sort'] == $name ? $_GET['dir'] : '') . '">' . $name . '</a> | ' ;
        }
        ?>
        </td>
        <td align=right><a href="<?php print $configData['tvbinz_rss']; ?>" target="_blank">TVBinz.net </a>|<a href="<?php print $configData['tvnzb_rss']; ?>" target="_blank"> TvNZB.com </a>|<a href="http://www.newzbin.com/browse/category/p/tv/" target="_blank"> Newzbin.com</a></td>
      </tr>
    </table>
  </div>
  <div id="listingWrapper">
<?php
//auto check for a newer version
if($config['check_for_update']) {
  $version = file_get_contents($configData['project_url']);
  if($version !== false) {
    $version = substr($version, strpos($version, 'Current Version:'));
    $version = substr($version, 0, strpos($version, '</strong'));
    $version = substr($version, strpos($version, '>') + 1);
    if(floatval($configData['version']) < floatval($version)) { ?>
    <div class="versionBox">A newer version of dPVR is out! <a target="_blank" href="<?php print $configData['project_url']; ?>"><img alt="download" src="images/download.png" /> Download version <strong><?php print $version; ?></strong></a></div>
    <?php }
  }
}
?>
<?php if(!file_exists($config['dpvr_dir'].$configData['xml_file'])) { ?>
    <div class="errorBox">TV show XML file not found! (<?php print $config['dpvr_dir'].$configData['xml_file']; ?>).<br /><br /><?php if (file_exists($config['dpvr_dir'].'tv.xml')) { ?><a href="index.php?op=convertXML">Click here</a> to import your tv.xml file<?php } else { ?>If you have a hellaVCR tv.xml file you can paste it into your dPVR folder to automatically import it.<? } ?></div>
<?php } ?>
<?php if($config['newzbin_handler'] == 'nzb' && !file_exists($config['nzb_queue'])) { ?>
    <div class="errorBox">NZB directory does not exist! (<?php print $config['nzb_queue']; ?>)</div>
<?php } ?>
<?php if($config['newzbin_handler'] == 'nzb' && ($config['newzbin_username'] == 'username' || strlen(trim($config['newzbin_username'])) == 0) && ($config['newzbin_password'] == 'password' || strlen(trim($config['newzbin_password'])) == 0)) { ?>
    <div class="errorBox">Newzbin account required to download NZB files!</div>
<?php } ?>
<?php if(!is_writeable('posters/')) { ?>
    <div class="errorBox">Posters directory is not writable! (<?php print getcwd(); ?>/posters/)</div>
<?php } ?>
<?php if(!is_writeable('logs/')) { ?>
    <div class="errorBox">Posters directory is not writable! (<?php print getcwd(); ?>/posters/)</div>
<?php } ?>
<?php if(!function_exists('curl_init')) { ?>
    <div class="errorBox">cURL is not installed! (please see <a target="_blank" href="http://php.net/curl">http://php.net/curl</a>)</div>
<?php } ?>
<?php
//check to make sure the file exists
if(file_exists($config['dpvr_dir'].$configData['xml_file'])) {

  //create a SimpleXML object
  $xml = simplexml_load_file($config['dpvr_dir'].$configData['xml_file']);

  $lastShowDay = "";
  $tooFarString = "More than one week";
  $unknownDateString = "Unknown";
  
  $shows = $xml->xpath('/tv/show');
  usort($shows, 'sortShows');
  
  $lastHeader = '';
  
  //loop over each show
  foreach($shows as $show) {
    $showID = htmlentities($show->attributes()->seriesID);
    $showDay = ucwords(strtolower(date('l', intval($show->nextAirdate))));
    
    //print day headers
    if($config['print_day_headers'] && $_GET['sort'] == 'upcoming') {
      //less than a week, print day
      if(intval($show->nextAirdate) < intval(strtotime("+1 week"))) {
        if($lastHeader != $showDay) {
          print '<br /><h1 class="day">' . $showDay . '</h1>';
          $lastHeader = $showDay;
        }
        
        // if we're on the current day then paint it accordingly
        if (date('m/d/Y') == date('m/d/Y', intval($show->nextAirdate))) {
          if ((int)$show->dfa_waiting == 1)
            $show_div_class = "listing_waiting";
          else
            $show_div_class = "listing_current";
        } else if (intval($show->nextAirdate) < intval(strtotime("now")))
          $show_div_class = "listing_overdue";
        else
          $show_div_class = "";
      }

      //who knows
      else if($show->nextAirdate == $configData['index']['unknown_timestamp'] && $lastHeader != $configData['index']['headers']['unknown']) {
        print '<br /><h1 class="day">' . $configData['index']['headers']['unknown'] . '</h1>';
        $lastHeader = $configData['index']['headers']['unknown'];
        $show_div_class = "listing_unknown";
      }
      
      //more than a week
      else if($show->nextAirdate < $configData['index']['unknown_timestamp'] && $lastHeader != $configData['index']['headers']['1week+']) {
        print '<br /><h1 class="day">' . $configData['index']['headers']['1week+'] . '</h1>';
        $lastHeader = $configData['index']['headers']['1week+'];
        $show_div_class = "listing_toofar";
      }

      // never
      else if (strtolower($show->status) == 'ended') {
        print '<br /><h1 class="day">' . $configData['index']['headers']['never'] . '</h1>';
        $lastHeader = $configData['index']['headers']['1week+'];
        $show_div_class = "listing_never";
      }
    }
?>
    <input type="hidden" id="listing_<?php print $showID; ?>_class" value="<? if ($config['index_colors'] && $_GET['sort'] == 'upcoming') print $show_div_class; ?>">
    <div class="<?php if ($config['index_colors'] && $_GET['sort'] == 'upcoming') print $show_div_class; ?>">
    <div class="listing" id="listing_<?php print $showID; ?>">
      <a name="<?php print $show->seriesName; ?>"></a>
      <?php
      //poster
      $poster = $show->poster;
      if(strlen($poster) > 0 && file_exists('posters/')) {
        $poster_image = substr($poster, strrpos($poster, '/') + 1);
        
        //cached image already exists
        if(file_exists('posters/' . $poster_image)) {
          $poster = 'posters/' . $poster_image;
        }
        //attempt to cache
        else {
          if(@copy($poster, 'posters/' . $poster_image) && file_exists('posters/' . $poster_image)) {
            $poster = 'posters/' . $poster_image;
          }
        }
      }
      
      ?>
      <img alt="" src="<?php print $poster; ?>" />
      <div id="info_<?php print $showID; ?>">
        <h1>
          <div class="icons">
            <a href="<?php print $configData['thetvdb']['show_link'].$show->attributes()->seriesID; ?>" target="_blank" title="<?php print $show->seriesName." @ thetvdb.com"; ?>"><img alt="" src="images/info.png" /></a>
            <?php if(!empty($show->attributes()->seriesID)) { ?>
            <a href="#<?php print $show->seriesName; ?>" title="Force Update" id="forceUpdate|<?php print $showID; ?>|<?php print $show->seriesName; ?>" class="forceUpdate"><img alt="" src="images/forceUpdate.png" id="forceUpdateImage|<?php print $showID; ?>" /></a>
            <a href="#" title="Edit <?php print htmlentities($show->seriesName); ?>" id="edit_<?php print $showID; ?>_link" class="editShow"><img alt="" src="images/edit.png" /></a>
            <a href="#" title="Delete <?php print htmlentities($show->seriesName); ?>" id="<?php print $showID; ?>|<?php print $show->seriesName; ?>" class="delShow"><img alt="" src="images/delete.png" /></a>
            <?php } ?>
          </div>
          <?php print $show->seriesName; ?>
        </h1>
        <?php
        $next_class = $downloaded_class = $status_class = $format_class = $language_class = '';
        
        
        // as long as we have something then use it
        if ((int)$show->dlSeason != 0 && (int)$show->dlEpisode != 0) {
          if ((int)$show->daily == 1 && (int)$show->dlAirdate !=0)
            $downloaded_episode = date('Y-m-d', (int)$show->dlAirdate).' ('.$show->dlSeason.'x'.sprintf('%02d', $show->dlEpisode).')'. ((int)$show->dlTimestamp==0?'':' @ '.date('h:ia l, F j', (int)$show->dlTimestamp));
          else
            $downloaded_episode = $show->dlSeason.'x'.sprintf('%02d', $show->dlEpisode).((int)$show->dlTimestamp==0?'':' @ '.date('h:ia l, F j', (int)$show->dlTimestamp));
        } else {
          $downloaded_episode = 'n/a';
          $downloaded_class = 'unknown';
        }

        //format status
        $status = $show->status;
        if(strlen(trim($status)) <= 0) {
          $status = 'n/a';
          $status_class = 'unknown';
        }
        
        //format next episode
        $next_episode = $show->next;
        if(strpos(strtolower($show->status), 'ended') !== false) {
          $next_episode = 'n/a (show ended)';
          $next_class = 'ended';
          $status_class = 'ended';
        }
        else if(empty($show->nextSeason) || empty($show->nextEpisode) && $show->daily != 1) {
          $next_episode = 'n/a';
          $next_class = 'unknown';
        } else if ((int)$show->daily == 1) {

          // since the lastDlAirdate is for display only we only update it here

          $next_episode = (!empty($show->nextAirdate) ? date("Y-m-d - ", (int)$show->nextAirdate) : '') . (!empty($show->nextEpName) ? $show->nextEpName : ''). ' ('.$show->nextSeason.'x'.$show->nextEpisode.')';
        } else
          $next_episode = $show->nextSeason."x".sprintf('%02d', $show->nextEpisode). (!empty($show->nextEpName) ? ' - "'.$show->nextEpName.'"' : '') . (!empty($show->nextAirdate) ? ' airs '.date('(l), F j, Y', (int)($show->nextAirdate)) : '');
        
        //format airs
        $airs = 'n/a';
        if(!empty($show->airs)) {
          $airs = date('g:i A l', (int)$show->airs);
          if(!empty($show->network)) {
            $airs .= ' on ' . str_replace("|", ", ", $show->network);
          }
        }
  
        ?>
        <p class="next">
          <span class="title">Next Episode:</span> <span class="info <?php print $next_class; ?>"><?php print $next_episode; ?></span>
        </p>
        <p class="noMargin">
          <span class="title">Downloaded Episode:</span> <span class="info <?php print $downloaded_class; ?>"><?php print $downloaded_episode; ?></span><br />
          <span class="title">Airs:</span> <span class="info <?php print $airs_class; ?>"><?php print $airs; ?></span><br />
          <span class="title">Format:</span> <span class="info <?php print $format_class; ?>"><?php print empty($show->format) ? 'any' : $GLOBALS['formats'][strval($show->format)]; print $show->dfa == 1 ? ' + first available':''; ?></span><br />
        </p>
      </div>
      <div id="edit_<?php print $showID; ?>" class="formWrapper editFormWrapper">
        <form id="editform_<?php print $showID; ?>" method="post" action="">
          <table cellpadding="0" cellspacing="0" border=0>
            <tr>
              <td colspan=2><h2><?php print htmlspecialchars_decode($show->seriesName); ?></h2><input type="hidden" id="edit_<?php print $showID; ?>_name" value="<?php print htmlspecialchars_decode($show->seriesName); ?>" /></td>
              <td rowspan="5" style="vertical-align: top;">
                <div id="postersWrapper_<?php print $showID; ?>" class="postersWrapper">
                  <a href="#" id="getPosters_<?php print $showID; ?>" class="getPosters" onclick="return getPoster('<?php print $showID; ?>');"><img alt="" src="images/download.png" /> Get Posters</a> <img class="postersLoading" id="postersLoading_<?php print $showID; ?>" alt="" src="images/loading_posters.gif" />
                  <div class="selectPosters" id="selectPosters_<?php print $showID; ?>"></div>
                </div>
              </td>
            </tr>
            <tr>
              <th colspan=2 style="text-align: left;">Download First Available: <input type="checkbox" name="dfa" id="edit_<?php print $showID; ?>_dfa" <?php print $show->dfa == 1 ? "checked" : ""; ?>/></td>
            </tr>
            <tr>
              <th>Last Episode:</th>
              <td>
                <?php if ((int)$show->daily == 1) { ?><input type="text" name="dlAirdate" size="8" value="<?php print date("Y-m-d", (int)$show->dlAirdate); ?>"><br />(ie. <?php print date("Y-m-d"); ?>)
                 <?php } else { ?><input type="text" name="dlSeason" size="2" value="<?php print $show->dlSeason; ?>" />&nbsp;x&nbsp;<input type="text" name="dlEpisode" size="2" value="<?php print $show->dlEpisode; ?>" /><?php } ?>
              </td>
            </tr>
            <tr>
              <th>Format:</th>
              <td>
                <select name="format">
                  <option value=""></option>
                  <?php foreach($GLOBALS['formats'] as $id => $format) { ?>
                  <option value="<?php print $id; ?>" <?php print $id == $show->format ? 'selected="selected"' : ''; ?>><?php print $format; ?></option>
                  <?php } ?>
                </select>
              </td>
            </tr>
            <tr>
              <td colspan=2><a href="#" id="edit_advanced_<?php print $showID; ?>_link" class="editAdvancedSettings">Advanced Settings >></a></td>
            </tr>
            <tr class="advancedEdit_<?php print $showID; ?>" style="display: none;">
              <td colspan=3>Submit a Newzbin report ID/URL to associate this show to a Newzbin report's TVRage URL</td>
            </tr>
            <tr class="advancedEdit_<?php print $showID; ?>" style="display: none;">
              <th>Newzbin Report URL/ID:</th>
              <td colspan=2><input type="text" id="edit_<?php print $showID; ?>_newzbinid" /> <input type="button" id="edit_<?php print $showID; ?>_doNewzbinID" class="editAdvancedScrapeNewzbin" value="Get Info" /></td>
            </tr>
            <tr class="advancedEdit_<?php print $showID; ?>" style="display: none;">
              <th>TVRage URL:</th>
              <td colspan=2>
                <div id="edit_<?php print $showID; ?>_tvrageurl_div"><?php print (!empty($show->tvrageurl)) ? "<a class=\"tvrage_link\" href=\"$show->tvrageurl\">".htmlspecialchars_decode($show->tvrageurl)."</a>" : "n/a"; ?></div>
                <input type="hidden" id="edit_<?php print $showID; ?>_tvrageurl" name="tvrageurl" value="<?php print $show->tvrageurl; ?>">
              </td>
            </tr>
            <tr>
              <td colspan=3  style="text-align: center;">
                <a href="#" id="addShow_<?php print $showID; ?>" class="addShow" onclick="$('editform_<?php print $showID; ?>').submit(); return false;"><img alt="" src="images/save.png" /> Save</a>
                <a href="#" id="cancelShow_<?php print $showID; ?>" class="cancelShow"><img alt="" src="images/cancel.png" /> Cancel</a>
              </td>
            </tr>
          </table>
          <input type="hidden" name="op" value="edit" />
          <input type="hidden" name="id" id="edit_<?php print $showID; ?>_id" value="<?php print $showID; ?>" />
          <input type="hidden" name="poster" value="<?php print $show->poster; ?>" />
          </form>
        </div>
      </div>
    </div>
<?php
  }
}
?>
  </div>
</div>
<script type="text/javascript">
var options = {
  script: "my.livesearch.php?",
  varname: "q",
  maxresults: 20,
  minchars: 2,
  shownoresults:false,
  json:true,
  cache:false,
  timeout:8000,
  callback: function (obj) {
    document.getElementById('addShowNameDiv').style.display = 'inline';
    document.getElementById('addShowName').style.display = 'none';
    document.getElementById('showID').value = obj.id;
    document.getElementById('showName').value = obj.value;
    document.getElementById('addShowNameText').innerHTML = obj.value;
    document.getElementById('postersWrapper').fireEvent('click');
  }
};
var as = new bsn.AutoSuggest('showNameSearch', options);
</script>

</body>
</html>
